package com.chaoyi.controller.ifs;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.chaoyi.dao.mysql.CartoonChapterMapper;
import com.chaoyi.dao.mysql.CartoonMapper;
import com.chaoyi.model.Cartoon;
import com.chaoyi.model.CartoonChapterVo;
import com.chaoyi.util.PageUtil;

@Controller
@RequestMapping("/cartoonIfs")
public class CartoonIfsController {
	@Resource
	CartoonMapper cartoonMapper;
	@Resource
	CartoonChapterMapper cartoonChapterMapper;

	/**
	 * 返回数据list
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getCartoonList")
	@ResponseBody
	public JSONObject getCartoonList(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		JSONObject json = new JSONObject();
		int page = 0;
		int pageSize = 0;
		try {
			page = Integer.parseInt(request.getParameter("page"));
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		} catch (Exception e) {
			page = 1;
			pageSize = 20;
		}
		if (page < 0) {
			page = 1;
		}
		if (pageSize < 0) {
			pageSize = 20;
		}
		List<Cartoon> list = cartoonMapper.findList(PageUtil.getOffset(page, pageSize) + "", pageSize + "");
		json.put("rows", list);
		return json;
	}
	/**
	 * 返回章节内容
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getCartoonChapterList")
	@ResponseBody
	public JSONObject getCartoonChapterList(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		JSONObject json = new JSONObject();
		int cartoonId = 1;
		try {
			cartoonId = Integer.parseInt(request.getParameter("cartoonId"));
		} catch (Exception e) {
			cartoonId = 1;
		}
		if(cartoonId < 1)
			cartoonId = 1;
		List<CartoonChapterVo> list = cartoonChapterMapper.findList(cartoonId);
		Map<Integer, List<CartoonChapterVo>> temp = list.stream().collect(Collectors.groupingBy(CartoonChapterVo::getChapterNum));
		json.put("rows", temp);
		return json;
	}
}
